const express = require('express');
const router = express.Router();
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
const upload = require('../multer/multer')

const { returnCardData, returnReaderData, returnSendComment,returnCommentList } = require('../utils/prismaData');
const { parseToken } = require('../utils/token');
const baseURL = process.env.BASE_URL


/* GET users listing. */
// 获取推荐文章数据
router.get('/hot', async (req, res) => {
    const articleData = await prisma.article.findMany({
        include: {
            tags: true,
            author: true,
            columns: true,
            follow: true,
        }
    })
    if (articleData === null) return res.status(404).send({ msg: '错误' })
    //   [ title, mainImg, content, authorId] +
    const data = articleData.filter(artical => artical.published === true).map(article => returnCardData(article))
    res.status(200).send(data)
});

// 获取指定id文章数据
router.get('/article', upload.none(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    if (req.query.articleId === undefined) return res.status(404).send({msg: '未找到资源'})
    const articleId = req.query.articleId
    await prisma.$transaction([
        prisma.article.findUnique({
            where: {
                id: articleId
            },
            select: {
                id: true,
                mainImg: true,
                content: true,
                title: true,
                createAt: true,
                author: true,
                views: true,
                follow: true
            },
        }),
        prisma.colunmArticle.findUnique({
            where: {
                articleId: articleId
            },
            select: {
                column: true
            },
        }),
        prisma.article.update({
            where: {
                id: articleId
            },
            data: {
                views: {
                    increment: 1
                }
            }
        })
    ]).then((result) => {
        result[0] = returnReaderData(result[0], id)
        res.status(200).send({...result[0], ...result[1]});
    }).catch((err) => {
        return res.status(404).send({msg: '未找到资源'})
    }).finally(async () => {
        await prisma.$disconnect();
    })
})

// 收藏一篇文章
router.post('/like', upload.none(), async (req, res) => {
    console.log('/article/like');
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { articleId, userId } = req.body
    if (id !== userId) return res.status(403).send({msg: '错误的用户信息'})
    const followArticle = await prisma.followArticle.upsert({
        where: {
            articleId_userId:{
                articleId: articleId,
                userId: id
            }
        },
        update: {},
        create: {
            articleId: articleId,
            userId: id
        }
    })
    if (followArticle === null) res.status(401).send({msg: '数据库操作错误'})
    res.status(200).send({msg: '已添加到收藏'})

})

// 点赞一条评论
router.post('/commentAcc', upload.none(), async (req, res) => {
    console.log('/article/commentAcc');
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { articleId, userId, commentId, isAcc } = req.body
    if (id !== userId) return res.status(403).send({msg: '错误的用户信息'})
    const comment = parseInt(commentId)
    const commentAcc = await prisma.commentAcc.upsert({
        where: {
            commentId_userId: {
                commentId: comment,
                userId: id
            }
        },
        update: {},
        create:{
            userId: id,
            commentId: comment
        }
    }).finally(async () => prisma.$disconnect())
    if(commentAcc === null) return res.status(401).send({msg: '操作错误'})
    res.status(200).send(commentAcc)
})

// 发布一条评论
router.post('/sendComment', upload.none(), async (req, res) => {
    console.log('/article/sendComment');
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const { userId, articleId, msg } = req.body
    if (id !== userId) return res.status(401).send({msg: '错误的用户信息'})
    await prisma.comment.create({
        data:{
            content: msg,
            userId: userId,
            articleId: articleId,
        }
    })
    .then(result => {
        res.status(200).send(returnSendComment(result))
    })
    .catch(err => {
        res.status(401).send({msg: '发布失败'})
    })
    .finally(async () => prisma.$disconnect())
})

// 查询所有的评论
router.get('/comments', upload.none(), async (req, res) => {
    const token = req.headers.authorization.split(' ')[1]
    const tokenData = await parseToken(token)
    if (!tokenData) return res.status(401).send({ msg: '登录过期' })
    const { id } = tokenData
    const {articleId} = req.query
    if (!articleId) return res.status(404).send({msg: '没有数据'})
    const commentsData = await prisma.comment.findMany({
        where: {
            articleId: articleId
        },
        include: {
            user: {
                select: {
                    id: true,
                    img: true,
                    name: true
                }
            },
            commentAcc: {
                select: {
                    userId: true,
                    commentId: true
                }
            }
        }
    })
    if (commentsData === null) return res.status(401).send({msg: '查询失败'})
    const result = returnCommentList(commentsData, id)
    res.status(200).send(result)
})

// 获取 指定专栏id下的文章数据
router.get('/columnArticles', upload.none(), async (req, res) => {
    console.log('/article/columnArticles');
    const { columnId } = req.query
    const articlesData = await prisma.colunmArticle.findMany({
        where: {
            columnId: columnId
        },
        select: {
            article: {
                include: {
                    tags: true,
                    author: true,
                    columns: true,
                    follow: true
                }
            }
        }
    }) 
    if (articlesData === null) return res.status(404).send({msg: '获取数据错误'})
    // 包装数据
    const result = articlesData.map(article => returnCardData(article.article))
    res.status(200).send(result);

})


// 获取指定 ids 数组的数据
router.get('/history', upload.none(), async (req, res) => {
    const { ids } = req.query
    const historyData = await prisma.article.findMany({
        where: {
            id: {
                in: ids
            }
        },
        include: {
            tags: true,
            author: true,
            columns: true,
            follow: true
        }
    })
    if (historyData === null) return res.status(404).send({msg: '获取数据错误'})
    const result = historyData.map(article => returnCardData(article))
    res.status(200).send(result);
})




module.exports = router;
